<?php

namespace cms\modules\v1\models\admin;

use cms\modules\v1\models\access\Module;
use cms\modules\v1\models\access\ModuleActions;
use cms\modules\v1\models\Common;
use common\models\Status;
use common\models\Functions;
use yii\base\Exception;

/**
 * This is the model class for table "project_info".
 *
 * @property int $id
 * @property string $name
 */
class AdminRole extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%admin_role}}';
    }

    public function getMapForApi($field = 'role_name')
    {
        $roleMap = static::getListMapByCache();
        $result = [];
        foreach ($roleMap as $v) {
            $result[] = [
                "id" => $v['id'],
                "name" => $v["role_name"]
            ];
        }

        return Functions::formatRestAPI(0, '', $result);
    }


    /**
     * 返回列表数据
     * @return array
     */
    public function getListData() {
        try {
            $where = [];

//            $count = self::getCountByWhere($where);
//            $data = static::setPageinationAPI($count, $page, $size);

//            $offset = ($page - 1) * $size;

            $list = static::getByWhere($where, ["*"], '');
            $moduleMap = Module::getListMapByCache();

//            $moduleMap = ArrayHelper::index($moduleMap, "id");

            $result = [];
            foreach($list as $k => $v) {
                $module = explode(",", $v['role_permissions']);
                $modules = [];
                foreach ($module as $vv) {
                    if (array_key_exists($vv, $moduleMap)) {
                        $modules[] = $moduleMap[$vv]['meta_title'];
                    }
                    if ($vv == -1) {
                        $modules[] = '超级管理员';
                    }
                }
                $moduleStr = implode(",", $modules);

                $actionStr = implode(",", ModuleActions::getDescByActionPermission($v['action_permissions']));
                $tmp = [
                    'id' => (int) $v['id'],
                    'roleName' => $v['role_name'],
                    'permission' => $moduleStr,
                    'actions' => $actionStr,
                    'status' => $v['status'],
                ];
                $result[] = $tmp;
            }

//            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getInfo($id = 0) {
        try {
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            $info = static::getOneInfoById($id);
            if (empty($info)) {
                throw new Exception('未知信息');
            }

            $data = [
                'id' => (int) $id,
                'role_name' => $info['role_name'],
                'status' => $info['status']
            ];

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function saveInfo() {
        try {
            $post = \Yii::$app->request->post();

            if (empty($post['role_name'])) {
                throw new Exception('角色名不能为空');
            }
            if (empty($post['role_permissions'])) {
                throw new Exception('权限不能为空');
            }
            if (empty($post['status'])) {
                throw new Exception('状态不能为空');
            }

            $permission = $this->getIviewPermission($post['role_permissions']);

            $data['role_name'] = trim($post['role_name']);
            if (in_array(-1, $post['role_permissions'])) {
                throw new Exception('厉害了我的哥，想篡位？');
            }
            $data['role_permissions'] = implode(",", $permission['role']);
            $data['action_permissions'] = implode(",", $permission['action']);
            $data['status'] = (int) $post['status'];

            $checkLoginName = static::getOneByWhere(['role_name' => $data['role_name']]);
            if ($post['id']) {
                if ($checkLoginName && $checkLoginName['id'] != $post['id']) {
                    throw new Exception('用户名重复');
                }
                $data['update_time'] = date('Y-m-d H:i:s');
                $res = static::updateDataWithLog($data, ['id' => $post['id']]);
                if ($res === false) {
                    throw new Exception('系统错误，请联系开发小哥哥');
                }
            } else {
                if ($checkLoginName) {
                    throw new Exception('用户名重复');
                }
                $data['create_time'] = date('Y-m-d H:i:s');
                $res = static::insertDataWithLog($data);
                if ($res === false) {
                    throw new Exception('系统错误，请联系开发小哥哥');
                }

            }
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getIviewPermission($permission = [], $result = ['role' => [], 'action' => []]) {

        foreach ($permission as $v) {
            if (!empty($v['children'])) {
                $children = $this->getIviewPermission($v['children'], $result);
                foreach ($children['role'] as $vv) {
                    if (!in_array($vv, $result['role'])) {
                        $result['role'][] = $vv;
                    }
                }
                foreach ($children['action'] as $vv) {
                    if (!in_array($vv, $result['action'])) {
                        $result['action'][] = $vv;
                    }
                }
            }
            if ($v['checked'] == 'true' && !in_array($v['id'], $result)) {
                if ($v['type'] == 1) {
                    $result['role'][] = $v['id'];
                }
                if ($v['type'] == 2) {
                    $result['action'][] = $v['id'];
                }
            }
        }

        $result['role'] = array_unique($result['role']);
        $result['action'] = array_unique($result['action']);
        return $result;
    }

    public function getTree($roleId = 0) {
        try {
            $roleId = (int) $roleId;
            $where['id'] = $roleId;
            $where['status'] = Status::COMMON_RADIO_YES;
            $permission = static::getOneByWhere($where);
            $permissions = explode(",", $permission['role_permissions']);
            $actionPermission = explode(",", $permission['action_permissions']);

            $list = $this->getAllCategoryForTree(0, $permissions, $actionPermission);

            return Functions::formatRestAPI(0, '', $list);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    public function getAllCategoryForTree($parentId = 0, $category = [], $actionPer = []) {
        $where['parent_id'] = $parentId;
        $where['status'] = Status::COMMON_RADIO_YES;
        $list = Module::getByWhere($where);
        $result = [];
        if (empty($list)) {
            return null;
        }
        $actionsM = new ModuleActions();
        foreach ($list as $v) {
            $tmp = [
                'id' => (int) $v['id'],
                'title' => $v['meta_title'],
                "type" => 1,
                'expand' => true,
                'checked' => in_array($v['id'], $category)
            ];


            $children = $this->getAllCategoryForTree($v['id'], $category, $actionPer);
            if (!empty($children)) {
                $tmp['children'] = $children;
            } else {
                //获取操作
                $actions = $actionsM->getChildrenByModuleId($v['id']);

                foreach ($actions as $vv) {
                    $ttmp = [
                        "id" => (int) $vv['id'],
                        "title" => $vv['desc'],
                        "type" => 2,
                        "expand" => false,
                        "checked" => in_array($vv['id'], $actionPer),
                    ];
                    $tmp['children'][] = $ttmp;
                }
            }
            $result[] = $tmp;
        }

        return $result;
    }


}
